from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from typing import List, Optional

from ..models.gen_column_model import GenColumn
from ..schemas.gen_column_schema import GenColumnCreate, GenColumnUpdate


class GenColumnService:
    @staticmethod
    async def create_gen_column(db: AsyncSession, gen_column_data: GenColumnCreate) -> GenColumn:
        """创建新的代码生成列"""
        new_gen_column = GenColumn(**gen_column_data.model_dump())
        db.add(new_gen_column)
        await db.commit()
        await db.refresh(new_gen_column)
        return new_gen_column

    @staticmethod
    async def get_gen_column_by_id(db: AsyncSession, gen_column_id: int) -> Optional[GenColumn]:
        """通过ID获取代码生成列"""
        result = await db.execute(select(GenColumn).where(GenColumn.id == gen_column_id))
        return result.scalars().first()

    @staticmethod
    async def get_all_gen_columns_by_business(db: AsyncSession, business_id: int) -> List[GenColumn]:
        """获取指定业务的所有代码生成列"""
        result = await db.execute(select(GenColumn).where(GenColumn.gen_business_id == business_id))
        return result.scalars().all()

    @staticmethod
    async def update_gen_column(
        db: AsyncSession, gen_column_id: int, gen_column_data: GenColumnUpdate
    ) -> Optional[GenColumn]:
        """更新代码生成列"""
        gen_column = await GenColumnService.get_gen_column_by_id(db, gen_column_id)
        if gen_column:
            update_data = gen_column_data.model_dump(exclude_unset=True)
            for key, value in update_data.items():
                setattr(gen_column, key, value)
            await db.commit()
            await db.refresh(gen_column)
        return gen_column

    @staticmethod
    async def delete_gen_column(db: AsyncSession, gen_column_id: int) -> bool:
        """删除代码生成列"""
        gen_column = await GenColumnService.get_gen_column_by_id(db, gen_column_id)
        if gen_column:
            await db.delete(gen_column)
            await db.commit()
            return True
        return False